package com.seari.controller;

import com.seari.bean.MenuPrivilege;
import com.seari.bean.User;
import com.seari.bean.UserRole;
import com.seari.pojo.DataGridBean;
import com.seari.pojo.MessageBean;
import com.seari.pojo.QueryUser;
import com.seari.service.RoleService;
import com.seari.service.UserRoleService;
import com.seari.service.UserService;
import com.seari.utils.JwtUtil;
import com.seari.utils.StringHelper;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author Rainbow
 */
@Controller
@RequestMapping("user/")
public class UserController
{
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    
    
    private final String ACCESS_TOKEN = "access_token";
    
    
    
    /**
	 * 验证token是否有效
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value = "/validToken", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object validToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String token = request.getParameter("token");
		boolean isAjax = CookieUtil.isAjax(request);
		if (StringUtils.isEmpty(token)) {
			if (isAjax) {
				map.put("code", "-1");
				map.put("msg", "error");
			}
			// 返回登录页面
		}
		CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
		checkAuthRequest.setToken(token);
		CheckAuthResponse checkAuthResponse = userService.validToken(checkAuthRequest);
		if ("00000".equals(checkAuthResponse.getCode())) {
			

		}
//		if (isAjax) {
			map.put("uid", checkAuthResponse.getUid());
			map.put("code", checkAuthResponse.getCode());
			map.put("msg", checkAuthResponse.getMsg());
			map.put("token", token);
//		}
		return map;
	}*/
    
	/*@RequestMapping(value="getUserByToken")
	@ResponseBody
	public Map<String,Object> getUserByToken(HttpServletRequest request)
	{
		Map<String,Object> result = new HashMap<String, Object>();
		String token = request.getParameter("token");
		if(StringUtils.isEmpty(token) && token.length()==0)
		{
			result.put("code", "FIAL");
			result.put("data", null);
			return result;
		}
		try {
			Map<String,Object> user = userService.getUserByToken(token);
			result.put("code", "SUCCESS");
			result.put("data", JSONObject.toJSON(user));
			if(user == null || user.size() == 0)
			{
				result.put("code", "ERROR");
				result.put("data", null);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "ERROR");
			result.put("data", null);
		}
		return result;
	}*/
    

	
    @RequestMapping("getUserByLogin")
    @ResponseBody
    public MessageBean getUserByLogin(HttpServletRequest req,HttpServletResponse resp)
    {
    	
    	//System.out.println("12314654");
        MessageBean mb = new MessageBean();
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        if(StringUtils.isBlank(userName) || StringUtils.isBlank(password))
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            resp.setHeader("Access-Control-Expose-Headers", ACCESS_TOKEN);
            mb.setMessage("用户名或密码为空");
            return mb;
        }
        User result = userService.getUserByLogin(userName, password);
        if(result != null )
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString().replace("-", ""), userName, Integer.valueOf(result.getUid().toString()));
        	resp.addHeader("access_token", jwt);
        	HashMap<String, String> tokenMap = new HashMap<String,String>();
        	tokenMap.put("token", jwt);
            mb.setData(tokenMap);

            req.getSession().setAttribute("userName",userName);
        }else
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("用户密码不匹配或无此用户");
        }
        //System.out.println(mb);
        return  mb;
    }

    /**
     * 通过token查询用户的所有信息
     * @param req
     * @return
     */
    @RequestMapping("getUserInfoByToken")
    @ResponseBody
    public DataGridBean<User> getUserInfoByToken(HttpServletRequest req)
    {
        DataGridBean<User> grid = new DataGridBean<User>();
        String token = req.getParameter("token");

        Claims claims = JwtUtil.parseJWT(token);
        QueryUser qu = new QueryUser();
        qu.setUid(Integer.parseInt(claims.get("uid").toString()));
        List<User> users = userService.getUserByUid(qu);
        grid.setRows(users);
        grid.setTotal(users.size());
        return  grid;
    }
    
    @RequestMapping("getMenuByToken")
    @ResponseBody
    public DataGridBean<MenuPrivilege> getMenuByToken(HttpServletRequest req,HttpServletResponse resp)
    {
        DataGridBean<MenuPrivilege> grid = new DataGridBean<MenuPrivilege>();
        String token = req.getParameter("token");

        Claims claims = JwtUtil.parseJWT(token);
        QueryUser qu = new QueryUser();
        qu.setUid(Integer.parseInt(claims.get("uid").toString()));
        List<Integer> roleIds = userService.getRoleIdByUid(qu);
        System.out.println(roleIds);
        List<MenuPrivilege> menuPrivileges = roleService.getMenuByUrids(roleIds);
        grid.setRows(menuPrivileges);
        grid.setTotal(menuPrivileges.size());
        return  grid;
    }
    
    @RequestMapping("getUserByUid")
    @ResponseBody
    public DataGridBean<User> getUserByUid(HttpServletRequest req)
    {
    	
        DataGridBean<User> grid = new DataGridBean<User>();
        String uid = req.getParameter("uid");
        QueryUser qu = new QueryUser();
        List<User> users = null;
        if(StringUtils.isNotBlank(uid))
        {
            qu.setUid(Integer.parseInt(uid));
            users = userService.getUserByUid(qu);
            grid.setRows(users);
            grid.setTotal(userService.getUserListCount(qu));
        }else{
        	grid.setMsg("error");
        	grid.setCode(1);
        }
        return  grid;
    }
    
    @RequestMapping("getUserByParams")
    @ResponseBody
    public DataGridBean<User> getUserByParams(HttpServletRequest req)
    {
        DataGridBean<User> grid = new DataGridBean<User>();
        String currPage = req.getParameter("page");
        String pageSize = req.getParameter("limit");
    	String match = req.getParameter("match");
    	String urid = req.getParameter("urid");
    	QueryUser qu = new QueryUser();
    	
        if(StringUtils.isNotBlank(currPage) && StringUtils.isNotBlank(pageSize))
        {
            qu.setStart((Integer.parseInt(currPage) - 1) * Integer.parseInt(pageSize));
            qu.setLimit(Integer.parseInt(pageSize));
        }
        List<User> users = null;
        if(StringUtils.isNotBlank(urid)
        	|| StringUtils.isNotBlank(match)){
        	qu.setMatch(match);
        	try{
        		qu.setUrid(Integer.parseInt(urid));
        	}catch(Exception e){
        		qu.setUrid(null);
        	}
        	users = userService.userSearch(qu);
        	grid.setRows(users);
            grid.setTotal(users.size());
       	return grid;
       }
        
        users = userService.getUserByParams(qu);
        grid.setRows(users);
        grid.setTotal(users.size());
        return  grid;
    }
    
    
    @RequestMapping("addUser")
    @ResponseBody
    public MessageBean addUser(HttpServletRequest req)  
    {
        MessageBean mb = new MessageBean();
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String[] urids = req.getParameterValues("urid[]");
        
        if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)
        		 || urids.length < 1)
        {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }
        QueryUser qu = new QueryUser();
        qu.setUserName(userName);
        int userCount = userService.checkUserExist(qu);
        if(userCount < 1)
        {
            //检查是否已存在此用户
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            int uuid = userService.addUser(user);
            
           int [] urid = new int[urids.length];
           for (int i = 0; i < urids.length; i++) {
        	   urid[i] = Integer.parseInt(urids[i]);
		}
            UserRole userRole = new UserRole();
            int intValue = user.getUid().intValue();
            userRole.setUuid(intValue);
            userRole.setUurid(urid);
            userRoleService.apportionRoles(userRole);
            
            if(uuid > 0)
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
                mb.setMessage("添加成功");
            }
            else
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("添加失败");
            }
        }else{
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("用户已存在");
        }
        return  mb;
        
    }
    
    @RequestMapping("updateUser")
    @ResponseBody
    public MessageBean updateUser(HttpServletRequest req)
    {
        MessageBean mb = new MessageBean();
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String[] urids = req.getParameterValues("urid[]");
        
        if(StringUtils.isBlank(uid)
        	|| StringUtils.isBlank(userName) 
        	|| ArrayUtils.isEmpty(urids))
        {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }
        
        int [] urid = new int[urids.length];
        for (int i = 0; i < urids.length; i++) {
     	   urid[i] = Integer.parseInt(urids[i]);
		}
        
        
        QueryUser qu = new QueryUser();
        User user  = new User();
        qu.setUid(Integer.parseInt(uid));
        qu.setUserName(userName);
        int userCount = userService.checkUserExist(qu);
        if(userCount < 1 )
        {
            //检查是否已存在此用户
            user.setUid(Long.parseLong(uid));
            user.setUserName(userName);
            user.setPassword(password);
            user.setUrids(urid);
            int resultNum = userService.updateUser(user);
            if(resultNum > 0)
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
                mb.setMessage("用户更新成功");
            }
            else
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("用户更新失败");
            }
        }else if(!StringUtils.isBlank(password)){
        	user.setUid(Long.parseLong(uid));
        	user.setPassword(password);
        	user.setUrids(urid);
        	int resultNum = userService.updateUser(user);
            if(resultNum > 0)
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
                mb.setMessage("密码更新成功");
            }
            else
            {
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("密码更新失败");
            }
        	
        }
        else
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("用户名已存在");
        }
        return mb;
    }
    
    @RequestMapping("deleteUser")
    @ResponseBody
    public MessageBean deleteUser(HttpServletRequest req)
    {
        MessageBean mb = new MessageBean();
        String uid = req.getParameter("uid");
        if(StringUtils.isBlank(uid))
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("用户ID缺失");
            return mb;
        }
        int resultNum = userService.deleteUser(Integer.parseInt(uid));
        if(resultNum < 0)
        {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("删除用户失败");
        }
        else{
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("删除用户成功");
        }
        return mb;
    }
}
